<template>
	<nav-header :title="isEditApply()?'咨询申请':'信息修改'">
		<view v-if="isEditApply() == false" class="bg-white p-4 mb-4 text-center">
			<view class="text-color-theme mb-4 text-left">用户名片</view>
			<my-upload v-model="headerImg" ref="myupload" :isSlot="true">
				<view slot="custom" class="relative">
					<image class="w-28 h-28 rounded-full" :src="headerImg.length == 0? './static/default_header.png':$util.formatImageIdUrl(headerImg[0].url)"
						 @click="$refs['myupload'].pickFile()"></image>
					<view v-if="headerImg.length > 0" class="absolute top-1_5 right-1_5" @click.stop="$refs['myupload'].clearFiles()">
						<u-icon name="close-circle-fill" size="20"></u-icon>
					</view>
				</view>
			</my-upload>
		</view>
		<view class="bg-white px-4 pt-4 pb-2 mb-4">
			<view class="text-color-theme mb-4">基本信息</view>
			<u-form :model="userInfo" :rules="rules" ref="uForm" labelWidth="80" labelAlign="center" :labelStyle="{color: '#666666'}">

        <u-form-item label="用户姓名" prop="realName" borderBottom required>
          <u-input v-model="userInfo.realName" border="none" placeholder="请输入联系人姓名" maxlength="10" :clearable="true"></u-input>
        </u-form-item>
        <u-form-item label="联系电话" borderBottom required>
          <u-input v-model="userInfo.phone" type="number" border="none" placeholder="请输入联系电话" maxlength="11" :clearable="true"></u-input>
        </u-form-item>

        <u-form-item label="职位" prop="posts" borderBottom >
          <u-input v-model="userInfo.posts" border="none" placeholder="请输入职位" maxlength="20" :clearable="true"></u-input>
        </u-form-item>
        <u-form-item label="所属单位" prop="firm" borderBottom required>
          <u-input v-model="userInfo.firm" border="none" placeholder="请输入公司名称" maxlength="30" :clearable="true"></u-input>
        </u-form-item>
        <u-form-item v-if="isEditApply()" label="申请时间" borderBottom>
          <div class="flex justify-between items-center" @click="dateObj.show = true">
            <text v-text="userInfo.businessTime || '请选择申请日期'" :class="{'text-gray-99': userInfo.businessTime? false:true}"></text>
            <u-icon :name="dateObj.show? 'arrow-down':'arrow-right'"></u-icon>
          </div>
        </u-form-item>
        <u-form-item v-if="isEditApply()" label="申请说明" prop="remark" borderBottom >
          <u-input v-model="userInfo.businessRemark" border="none" placeholder="请输申请说明" maxlength="300" :clearable="true"></u-input>
        </u-form-item>
        <u-form-item v-else label="备注" prop="remark" borderBottom >
          <u-input v-model="userInfo.remark" border="none" placeholder="请输备注" maxlength="300" :clearable="true"></u-input>
        </u-form-item>
      <view class="text-color-theme mb-4">其他信息</view>
        <u-form-item label="昵称" prop="nickName" borderBottom >
          <u-input v-model="userInfo.nickName" border="none" placeholder="请输入昵称" maxlength="10" :clearable="true"></u-input>
        </u-form-item>
				<u-form-item label="性别" borderBottom>
					<div class="flex justify-between items-center" @click="sexObj.show = true">
						<text v-text="sexObj.list[parseInt(userInfo.gender)].name"></text>
						<u-icon :name="sexObj.show? 'arrow-down':'arrow-right'"></u-icon>
					</div>
				</u-form-item>
        <u-form-item v-if="isEditApply() === false" label="出生日期" borderBottom>
          <div class="flex justify-between items-center" @click="dateObj.show = true">
            <text v-text="userInfo.birthday || '请选择出生日期'" :class="{'text-gray-99': userInfo.birthday? false:true}"></text>
            <u-icon :name="dateObj.show? 'arrow-down':'arrow-right'"></u-icon>
          </div>
        </u-form-item>
        <u-form-item label="电子邮箱" prop="email" borderBottom >
          <u-input v-model="userInfo.email" border="none" placeholder="请输入电子邮箱" maxlength="30" :clearable="true"></u-input>
        </u-form-item>
			</u-form>
		</view>
		<view  class="bg-theme w-full py-4 flex items-center justify-around fixed bottom-0 z-50 text-white" @click="submit" v-text="isEditApply()?'提交':'保存'"></view>
		<u-action-sheet :actions="sexObj.list" title="选择性别" :show="sexObj.show" cancelText="取消" @select="(item)=>{
			userInfo.gender = item.val
		}" @close="sexObj.show = false"></u-action-sheet>
		<u-datetime-picker  :show="dateObj.show" v-model="dateObj.val" :minDate="isEditApply()? dateObj.minOffDate: dateObj.minDate" :maxDate="isEditApply()? dateObj.maxOffDate: dateObj.maxDate" mode="date" @confirm="popupConfirm" @cancel="dateObj.show = false"></u-datetime-picker>
		<u-toast ref="uToast"></u-toast>
	</nav-header>
</template>

<script>
	import {mapState} from 'vuex'
	import NavHeader from '@/components/nav_header.vue'
	import MyUpload from '@/components/my_upload.vue'
	import * as uploadApi from '@/interface/common/upload.js'
	import * as authUserApi from '@/interface/auth/authUserApi.js'
	export default {
		components: {
			NavHeader,MyUpload
		},
		data() {
			let today = new Date()
			let officeDay = new Date()
			today.setFullYear(today.getFullYear() - 60)
      officeDay.setFullYear(officeDay.getFullYear() + 1)
			return {
        businessId: '',
        businessType: '',
        businessName: '',
				sexObj: {
					show: false,
					list: [{name: '保密', val: '0'}, {name: '男性', val: '1'}, {name: '女性', val: '2'}],
				},
				dateObj: {
					val: '',
					show: false,
					minDate: Number(today),
					maxDate: Number(new Date()),
          minOffDate: Number(new Date()),
          maxOffDate: Number(officeDay)
				},
				headerImg: [],
				userInfo: {
					phone: '',
					gender: '0',
					birthday: '',
					nickName: '',
          realName: '',
					avatarUrl: '',
          firm: '',
          email: '',
          posts: '',
          businessType: '',
          businessId: '',
          businessTime: '',
          businessName: '',
          businessRemark: '',
				},
				rules: {
					nickName: {
						type: 'string',
						required: true,
						message: '请填写昵称',
						trigger: ['blur', 'change']
					},
          realName: {
            type: 'string',
            required: true,
            message: '请填写联系人姓名',
            trigger: ['blur', 'change']
          },
          phone: {
            type: 'string',
            required: true,
            message: '请填写联系电话',
            trigger: ['blur', 'change']
          },
          firm: {
            type: 'string',
            required: true,
            message: '请填写公司名称',
            trigger: ['blur', 'change']
          },
				},
			}
		},
		computed: {
			...mapState({
				user: state => state.user
			})
		},
    onLoad(e) {
      const v = this
      v.initData()
      v.businessId = e.businessId
      v.businessType = e.businessType
      v.businessName = e.businessName
    },
		onReady(e) {
			this.initData()
		},
		methods: {
			initData () {
				authUserApi.getUserInfo().then(res=>{
					if (res.success) {
						for (let key in res.data) {
							let val = res.data[key]
							if (this.$util.isBlank(val)) res.data[key] = ''
						}
						Object.assign(this.userInfo, res.data)
						if (this.userInfo.avatarUrl) this.headerImg.push({url: this.userInfo.avatarUrl})
            // 会议的值
            if(this.isEditApply()){
              this.userInfo.businessId = this.businessId
              this.userInfo.businessType = this.businessType
              this.userInfo.businessName = this.businessName
            }
					}
				})
			},
			async submit() {
				const v = this
				// 有图片需要上传
				if (v.headerImg.length > 0) v.userInfo.avatarUrl = await uploadApi.startEasyUpload(v.headerImg)
				v.$refs.uForm.validate().then(res => {
					v.$util.showLoading('正在保存用户信息...')
					authUserApi.updateUserInfo(v.userInfo).then(res=>{
						v.$store.dispatch('updateUserInfo', {
							status: '1',
							type: 'user',
							userName: v.userInfo.nickName,
							avatarUrl: v.userInfo.avatarUrl
						})
            if (res.success) {
              v.$refs.uToast.show({
                message: v.isEditApply()?'申请成功.实际申请情况，以服务人员通知为准!': '保存成功.',
                complete() {
                  uni.navigateBack()
                }
              })
            }

					}).finally(()=>{
						v.$util.hideLoading()
					})
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
      popupConfirm(date){
        if(this.isEditApply()){
          this.userInfo.businessTime = this.$util.getFormatDate(date.value, "yyyy-0m-0d")
        }else {
          this.userInfo.birthday = this.$util.getFormatDate(date.value, "yyyy-0m-0d")
        }
        this.dateObj.show = false
      },
      // 是否编辑用户信息
      isEditApply(){
        let isEditApply = false;
        isEditApply = (this.businessType === 'officeApply'  || this.businessType === 'companyApply' || this.businessType === 'companyProjectApply' || this.businessType === 'companyProductApply' || this.businessType === 'placeApply');
        return isEditApply;
      },
		}
	}
</script>

<style>
	page{
		background-color: #f7f7f7;
	}
</style>
